# -*- coding: utf-8 -*-
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib.auth.models import User, Group
from django.db.models import Count
from django.contrib import messages
from django.core.paginator import Paginator
from .. import views


def is_admin(user):
    return user.is_superuser
    # return user.groups.filter(name='Admin').exists()


@login_required
@user_passes_test(is_admin, login_url='/login/')
def admin_dashboard_view(request):
    # 获取一些统计数据
    total_users = User.objects.count()
    regular_users = User.objects.filter(groups__name='Regular User').count()
    admin_users = User.objects.filter(groups__name='Admin').count()

    context = {
        'total_users': total_users,
        'regular_users': regular_users,
        'admin_users': admin_users,
        'user': request.user,
    }
    return render(request, 'admin/admin_dashboard.html', context)


@login_required
@user_passes_test(is_admin, login_url='/login/')
def user_management_view(request):

    # 处理用户组变更
    if request.method == 'POST':
        user_id = request.POST.get('user_id')
        action = request.POST.get('action')

        if user_id and action:
            try:
                user = User.objects.get(id=user_id)
                if action == 'make_admin':
                    admin_group = Group.objects.get(name='Admin')
                    user.groups.add(admin_group)
                    messages.success(request, f'用户 {user.username} 已被设为管理员')
                elif action == 'remove_admin':
                    admin_group = Group.objects.get(name='Admin')
                    user.groups.remove(admin_group)
                    messages.success(request, f'已移除 {user.username} 的管理员权限')
                elif action == 'delete':
                    if user != request.user:  # 防止删除自己
                        username = user.username
                        user.delete()
                        messages.success(request, f'用户 {username} 已被删除')
                    else:
                        messages.error(request, '不能删除当前登录的用户')
            except User.DoesNotExist:
                messages.error(request, '用户不存在')
            except Group.DoesNotExist:
                messages.error(request, '用户组不存在')

    # 获取所有用户
    users = User.objects.all().order_by('-date_joined')
    # 分页
    page = request.GET.get('page', 1)
    paginator = Paginator(users, 10)  # 每页显示10个用户
    users_page = paginator.get_page(page)
    context = {
        'users': users_page,
        'user': request.user,
    }
    return render(request, 'admin/user_management.html', context)


@login_required
@user_passes_test(is_admin, login_url='/login/')
def data_management_view(request):
    # 获取上传的文件统计
    import os
    from django.conf import settings

    media_path = os.path.join(settings.BASE_DIR, 'media')
    files = []

    if os.path.exists(media_path):
        for file in os.listdir(media_path):
            if file.endswith('.xlsx'):
                file_path = os.path.join(media_path, file)
                file_stat = os.stat(file_path)
                files.append({
                    'name': file,
                    'size': file_stat.st_size,
                    'created': file_stat.st_ctime,
                    'modified': file_stat.st_mtime,
                })

    context = {
        'files': sorted(files, key=lambda x: x['modified'], reverse=True),
        'user': request.user,
    }
    return render(request, 'admin/data_management.html', context)
